package org.agile4j.springframework.annotation;

import org.apache.commons.collections4.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;



/**
 * 校验工具类
 * @author hyx
 * 
 */
public class ValidationUtils {
	private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator() ;

	/**
	 * 校验entity是否符合设定
	 * @param t 校验entity
	 * @return ValidationResult
	 */
	public static<T> ValidationResult validateEntity(T t) {
		ValidationResult result = new ValidationResult() ;
		// 校验结果集
		Set<ConstraintViolation<T>> constraintViolation = validator.validate(t, Default.class) ;
		if(CollectionUtils.isNotEmpty(constraintViolation)) {
			result.setHasErrors(true);
			Map<String, String> errorMsgMap = new HashMap<> () ;
			for(ConstraintViolation<T> cv : constraintViolation) {
				errorMsgMap.put(cv.getPropertyPath().toString(), cv.getMessage()+", 而现在是：" +cv.getInvalidValue()) ;
			}
			result.setErrorMsg(errorMsgMap);
		}
		return result ;
	}
	
	/**
	 * 校验entity的属性是否符合设定
	 * @param t 校验entity
	 * @param propertyName 属性名
	 * @return ValidationResult
	 */
	public static<T> ValidationResult validateProperty(T t, String propertyName) {
		ValidationResult result = new ValidationResult() ;
		// 校验结果集
		Set<ConstraintViolation<T>> constraintViolation = validator.validateProperty(t, propertyName, Default.class) ;
        if(CollectionUtils.isNotEmpty(constraintViolation)) {
			result.setHasErrors(true);
			Map<String, String> errorMsgMap = new HashMap<String, String> () ;
			for(ConstraintViolation<T> cv : constraintViolation) {
				errorMsgMap.put(cv.getPropertyPath().toString(), cv.getMessage()+", 而现在是：" +cv.getInvalidValue()) ;
			}
			result.setErrorMsg(errorMsgMap);
		}
		return result ;
	}
}
